<template>
    <div class="main commodity-tag-list">
        <div v-if="rightsButtons['add']" class="tool-bar">
            <el-button type="success" icon="el-icon-plus" class="fr" @click="showAdd">新建一级分类</el-button>
        </div>
        <tree-table :data="list" v-loading="listLoading" :columns="columns" :evalArgs="args" :expandAll="true" border>
            <el-table-column align="center" label="是否可用" width="100">
                <template slot-scope="scope">
                    <span>{{scope.row.categoryStatus == 1 ? '可用' : '不可用'}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="排序" width="80" prop="sort"></el-table-column>
            <el-table-column align="left" label="操作" width="260" v-if="rightsButtons['addSub'] || rightsButtons['edit'] || rightsButtons['delete']">
                <template slot-scope="scope">
                    <el-button v-if="rightsButtons['addSub']&&scope.row._level < 6" type="success" size="mini" @click="showAdd(scope.row)">新建子类</el-button>
                    <el-button v-if="rightsButtons['edit']" type="primary" size="mini" @click="showEdit(scope.row)">编辑</el-button>
                    <el-button v-if="rightsButtons['delete'] && (scope.row.parentId || !scope.row.ifGoods)" type="danger" size="mini" @click="del(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </tree-table>
        <el-dialog :title="editItem.id ? '编辑分类' : '新建分类'" :visible.sync="showEditPop">
            <el-form :model="editItem" :rules="editRule" size="medium" ref="editItem" label-width="120px">
                <el-form-item label="分类名称:" prop="name">
                    <el-input v-model="editItem.name"></el-input>
                </el-form-item>
                <el-form-item v-if="editItem.parentId" label="分类商品排序:" prop="goodsOrderBy">
                    <el-select v-model="editItem.goodsOrderBy">
                      <el-option label="商品销量" :value="1"></el-option>
                      <el-option label="商品创建时间" :value="2"></el-option>
                      <el-option label="商品修改时间" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上级分类:">
                    <span v-text="editItem.parentId ? editItem.parentName : '顶级分类'"></span>
                </el-form-item>
                <el-form-item label="排序:">
                    <el-input type="number" v-model="editItem.sort"></el-input>
                </el-form-item>
                <el-form-item label="子标题:">
                    <el-input v-model="editItem.subtitle"></el-input>
                </el-form-item>
                <el-form-item label="分类介绍:">
                    <el-input v-model="editItem.intro"></el-input>
                </el-form-item>
                <el-form-item label="ICON:">
                    <el-upload
                            class="avatar-uploader"
                            accept="image/*"
                            :action="upladUrl"
                            name="file"
                            :show-file-list="false"
                            :on-success="uploadIconSuccess"
                            :before-upload="beforeUpload">
                        <img v-if="editItem.smallPic" :src="editItem.smallPic" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="banner:">
                    <el-upload
                            class="avatar-uploader"
                            accept="image/*"
                            :action="upladUrl"
                            name="file"
                            :show-file-list="false"
                            :on-success="uploadSuccess"
                            :before-upload="beforeUpload">
                        <img v-if="editItem.banner" :src="editItem.banner" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="是否可用:">
                    <el-switch
                            v-model="editItem.categoryStatus"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            :active-value="1"
                            :inactive-value="0">
                    </el-switch>
                </el-form-item>

                <!--<el-form-item label="banner:">-->
                <!--<el-input v-model="editItem.banner"></el-input>-->
                <!--</el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" :disabled="btnDisabled">保存</el-button>
                <el-button @click="showEditPop = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
  import treeTable from '@/components/TreeTable'

  export default {
    name: 'commodityCategory',
    data() {
      const validTagName = (rule, value, callback) => {
        if(!value){
          return callback(new Error('不能为空'));
        }
        if (this.editItem.id && this.editName === value) {
          return callback();
        }
        if(/[^\a-zA-Z0-9\u4e00-\u9FA5\-.]/.test(value)){
          return callback(new Error('不能含有特殊字符'));
        }
        if(value.length > 100){
          return callback(new Error('不能超过100字符'));
        }
        this.btnDisabled = true;
        this.request({
          url: '/bsnl-product/category/name',
          method: 'get',
          params: {
            name: value
          }
        }).then(({data}) => {
          if (data && data.id) {
            callback(new Error('分类名已存在'));
          } else {
            this.btnDisabled = false;
            callback();
          }
        }).catch(err => {
          this.btnDisabled = false;
          callback(new Error(err));
        });
      };
      return {
        list: [],
        columns: [
          {
            text: '名称',
            value: 'name'
          },
        ],
        args: [null, null, 'name'],
        params: {
          name: ''
        },
        query: {},
        page: 1,
        pageSize: 20,
        total: 0,
        editItem: {},
        editName: '',
        editRule: {
          name: [
            {required: true, message: '不能为空', trigger: 'change'},
            {max: 100, message: '不能超过100字符', trigger: 'change'},
            {pattern: /[\a-zA-Z0-9\u4e00-\u9FA5\-.]+$/, message: '不能含有特殊字符', trigger: 'change'},
            {validator: validTagName, trigger: 'blur'}
          ]
        },
        showEditPop: false,
        listLoading: false,
        btnDisabled: false,
      }
    },
    created() {
      this.getList();
    },
    methods: {
      // 获取列表
      getList() {
        this.listLoading = true;
        this.request({
          url: '/bsnl-product/category/tree',
          method: 'get'
        }).then(({data}) => {
          this.list = data ? data : [];
          this.list.map(item => {
            item.ifGoods = item.children.filter(subItem => subItem.ifGoods>0).length
          });
          this.listLoading = false;
        }).catch(err => {
          this.list = [];
          this.listLoading = false;
        });
      },
      // 获取详情
      getInfo(id) {
        this.request({
          url: '/bsnl-product/category/' + id,
          method: 'get',
          params: {id}
        }).then(({data}) => {
          this.$set(this.editItem, 'parentName', data ? data.name : '');
        }).catch(err => {
          this.editItem.parentName = '';
          this.showEditPop = false;
        });
      },
      // 删除
      del(item) {
        this.$confirm(`确定要删除 ${item.name} ${item.children && item.children.length > 0 ? '及其子类' : ''}吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.request({
            url: '/bsnl-product/category/delete',
            method: 'post',
            data: {
              id: item.id,
              deleteFlag: 0
            },
            headers: {
              authorKey: `${this.$route.name}Delete`
            }
          }).then(() => {
            this.$message.success('删除成功');
            this.getList();
          });
        }).catch(err => {
          console.log(err);
        });
      },
      // 显示新建
      showAdd(item) {
        this.editItem = {
          name: '',
          goodsOrderBy: 1,
          parentId: 0,
          parentName: '',
          subtitle: '',
          smallPic: '',
          intro: '',
          sort: '',
          banner: '',
          categoryStatus: 0,
        };
        if (item && item.id) {
          this.editItem.parentId = item.id;
          this.editItem.parentName = item.name;
        }
        this.showEditPop = true;
        this.btnDisabled = false;
      },
      // 显示编辑
      showEdit(item) {
        this.editItem = {...item};
        this.editName = item.name;
        if (item && item.parentId) {
          this.getInfo(item.parentId);
        }
        this.showEditPop = true;
        this.btnDisabled = false;
      },
      uploadIconSuccess(res, file){
        this.$set(this.editItem, 'smallPic', this.replaceImgUrl(res.filePath));
      },
      uploadSuccess(res, file){
        this.$set(this.editItem, 'banner', this.replaceImgUrl(res.filePath));
      },
      // 保存
      save() {
        this.$refs.editItem.validate(valid => {
          if (!valid) {
            return false;
          }
          const {id, name, goodsOrderBy, parentId, subtitle, smallPic, intro, sort, banner, categoryStatus} = this.editItem;
          let url = id ? '/bsnl-product/category/update' : '/bsnl-product/category/create';
          this.btnDisabled = true;
          this.request({
            url,
            method: 'post',
            data: {
              id,
              name,
              goodsOrderBy,
              parentId,
              subtitle,
              smallPic,
              intro,
              sort,
              banner,
              categoryStatus
            },
            headers: {
              authorKey: id ? `${this.$route.name}Edit`:`${this.$route.name}${parentId ?'AddSub': 'Add'}`
            }
          }).then(() => {
            this.btnDisabled = false;
            this.editItem = {};
            this.showEditPop = false;
            this.$message.success('保存成功');
            this.getList();
          }).catch(err => {
            console.log(err);
            this.btnDisabled = false;
          });
        });
      },
      // 搜索
      search() {
        this.page = 1;
        this.query = {
          ...this.params
        };
        this.getList();
      },
      // 切换分页
      handleCurrentChange(page) {
        this.page = page;
        this.getList();
      },
    },
    components: {
      treeTable
    }
  }
</script>
